// pages/product/share_detail.js
var app = getApp();
//引入这个插件，使html内容自动转换成wxml内容
var WxParse = require('../../wxParse/wxParse.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    detail: [],
    goodsurl: app.d.hostUrl + app.d.goodsurl,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    that.setData({
      productId: options.productId,
    });
    this.loadProductDetail();
  },

  // 商品详情数据获取
  loadProductDetail: function () {
    var that = this;
    wx.request({
      url: app.d.hostUrl + 'wapi/product_index.html',
      method: 'post',
      data: {
        id: that.data.productId,
      },
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        //--init data 
        var status = res.data.ret;
        if (status == 0) {
          var pro = res.data.data;
          WxParse.wxParse('content', 'html', pro.goods.goods_content, that, 3);
          //var content = pro.goods.goods_content;
          //that.initProductData(data);
          that.setData({
            detail: pro.goods,
            //attrValueList:res.data.data.attrValueList,
          });
        } else {
          wx.showToast({
            title: res.data.err,
            duration: 2000,
          });
        }
      },
      error: function (e) {
        wx.showToast({
          title: '网络异常！',
          duration: 2000,
        });
      },
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: '极好生活商城',
      path: '/pages/index/index?scene=invite%3D' + app.globalData.user_id,
      success: function (res) {
        wx.showToast({
          title: '分享成功',
          duration: 2000
        });
      },
      fail: function (res) {
        // 分享失败
      }
    }
  },
  share_now:function(){
    var that = this;
    wx.request({
      url: app.d.hostUrl + 'wapi/get_share_prize.html',
      method: 'post',
      data: {
        id: that.data.productId,
        seesionid: app.globalData.userInfo.sessionId,
        openid: app.globalData.userInfo.openid,
      },
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        var status = res.data.ret;
        if (status == 0) {
          if(res.data.data.length > 0){
            wx.showToast({
              title: res.data.data,
              duration: 2000,
            });
          }
        } else {
          wx.showToast({
            title: res.data.msg,
            duration: 2000,
          });
        }
      },
      error: function (e) {
        wx.showToast({
          title: '网络异常',
          duration: 2000,
        });
      },
    });
  },

  //先制作一个canvas标签，再保存成图片
  onSaveImg: function () {
    var that = this;

    wx.request({
      url: app.d.hostUrl + 'wapi/get_share_prize.html',
      method: 'post',
      data: {
        id: that.data.productId,
        seesionid: app.globalData.userInfo.sessionId,
        openid: app.globalData.userInfo.openid,
      },
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        var status = res.data.ret;
        if (status == 0) {
          if (res.data.data != undefined) {
            wx.showToast({
              title: res.data.data,
              duration: 2000,
            });
          }
        }
        setTimeout(function () {
          that.create_qrcoce();
        }, 2000)
        
      },
      error: function (e) {
        wx.showToast({
          title: '网络异常！',
          duration: 2000,
        });
      },
    });
    
  },
  create_qrcoce:function(){
    var that = this;
    //生成二维码和图片开始
    wx.request({
      url: app.d.hostUrl + 'wapi/get_qrcode.html',
      method: 'post',
      data: {
        id: that.data.productId,
        seesionid: app.globalData.userInfo.sessionId,
        openid: app.globalData.userInfo.openid,
      },
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        if (res.data.ret == 0) {
          that.setData({ qrcode: res.data.data });
          //that.create_qrcode(res.data.data);
          that.getAvaterInfo();
        }
        //endInitData
      },
      fail: function (e) {
        wx.showToast({
          title: '网络异常！',
          duration: 2000
        });
      }
    })



  },
  getAvaterInfo: function () {
    wx.showLoading({ title: '生成中50%...', mask: true, });
    var that = this;

    wx.downloadFile({
      url: that.data.goodsurl + that.data.detail.goods_image,
      success: function (res) {
        wx.hideLoading();
        if (res.statusCode === 200) {
          var goodsSrc = res.tempFilePath;
          that.getQrCode(goodsSrc);
        } else {
          wx.showToast({
            title: '商品图片下载失败！',
            icon: 'none',
            duration: 2000,
            success: function () {
              that.getQrCode();//回调另一个图片下载
            }
          })
        }
      }
    })
  },
  getQrCode: function (goodsSrc) {
    wx.showLoading({ title: '生成中100%...', mask: true, });
    var that = this;
    wx.downloadFile({
      url: that.data.qrcode,
      success: function (res) {
        wx.hideLoading();
        if (res.statusCode === 200) {
          var codeSrc = res.tempFilePath;
          that.create_qrcode(goodsSrc, codeSrc);//真正的绘图方法
        } else {
          wx.showToast({
            title: '二维码下载失败！',
            icon: 'none',
            duration: 2000,
            success: function () {
              var codeSrc = "";
              that.sharePosteCanvas();//真正的绘图方法
            }
          })
        }
      }
    })
  },
  create_qrcode: function (goodsSrc, codeSrc){
    var that = this;
    const ctx = wx.createCanvasContext('myCanvas');//看回wxml里的canvas标签，这个的myCanvas要和标签里的canvas-id一致
    ctx.clearRect(0, 0, 644, 966);
    ctx.drawImage('../../images/whitebg.png', 0, 0, 500, 700, 0, 0)
    //ctx.drawImage(that.data.goodsurl + that.data.detail.goods_image, 10, 10, 370, 400, 100, 100);
    ctx.drawImage(goodsSrc, 10, 10, 480, 400, 100, 100);
    //ctx.drawImage(qrcode, 100, 100, 400, 400, 100, 100);
    ctx.setFontSize(26);
    ctx.fillText(that.data.detail.goods_name, 20, 450);
    ctx.setTextAlign("center");
    ctx.setFillStyle("#f00");
    ctx.fillText('￥' + that.data.detail.now_price, 60, 490);


    ctx.moveTo(10, 510)
    ctx.lineTo(475, 510)
    ctx.setStrokeStyle('#A2A2A2')
    ctx.stroke()
    ctx.draw()

    ctx.setTextAlign("left");
    ctx.setFillStyle("black");
    ctx.setFontSize(18);
    ctx.fillText("长按识别小程序码访问", 20, 550);
    ctx.setFontSize(16);
    ctx.setFillStyle("#A1A1A1");
    ctx.fillText("随意礼品商城", 20, 585);

    ctx.drawImage(codeSrc, 255, 520, 180, 180, 100, 100);

    var self = this;

    ctx.draw(true, setTimeout(function () {     //为什么要延迟100毫秒？大家测试一下
      wx.canvasToTempFilePath({
        x: 0,
        y: 0,
        width: 646,
        height: 966,
        destWidth: 646,
        destHeight: 966,
        canvasId: 'myCanvas',
        success: function (res) {
          self.data.savedImgUrl = res.tempFilePath;
          self.saveImageToPhoto();
        }
      })
    }, 100))
    //生成二维码和图片结束
  },
  //保存图片到相册
  saveImageToPhoto: function () {
    if (this.data.savedImgUrl != "") {
      wx.saveImageToPhotosAlbum({
        filePath: this.data.savedImgUrl,
        success: function () {
          wx.showModal({
            title: '保存图片成功',
            content: '收藏成功',
            showCancel: false
          });
        },
        fail: function (res) {
          if (res.errMsg == "saveImageToPhotosAlbum:fail cancel") {
            wx.showModal({
              title: '保存图片失败',
              content: '您已取消保存图片到相册！',
              showCancel: false
            });
          } else {
            wx.showModal({
              title: '提示',
              content: '保存图片失败，您可以点击确定设置获取相册权限后再尝试保存！',
              complete: function (res) {
                if (res.confirm) {
                  wx.openSetting({})      //打开小程序设置页面，可以设置权限
                } else {
                  wx.showModal({
                    title: '保存图片失败',
                    content: '您已取消保存图片到相册！',
                    showCancel: false
                  });
                }
              }
            });
          }
        }
      })
    }
  },
})